//
//  ChoiceViewController.m
//  Choice
//
//  Created by A-01 on 2020/6/15.
//  Copyright © 2020 Mac. All rights reserved.
//

#import "ChoiceViewController.h"
#import "ChoiceTableViewCell.h"
#import "AddOpinionsViewController.h"
#import "ShakeViewController.h"
#import "NumberCollectionViewCell.h"

@interface ChoiceViewController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, weak)UICollectionView * collectionView;
@property (nonatomic, weak)UIButton * startButton;
@property (nonatomic, weak)UISegmentedControl *segment;
@property (nonatomic, strong)NSArray * dataList;
@property (nonatomic, strong)NSArray * colorArray;
@property (nonatomic, weak)UILabel * exploreLabel;
@property (nonatomic, weak)UIToolbar *toolbar;
@property (nonatomic, weak)UIView * whiteView;

@end

@implementation ChoiceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"Choice";
    self.view.backgroundColor = ZRWhiteColor;
    [self setupUI];    
}

-(void)viewWillAppear:(BOOL)animated{
    
    [self loadData];
}


- (void)loadData{
    
    self.dataList = [[NSUserDefaults standardUserDefaults] objectForKey:self.type];
}

- (void)setDataList:(NSArray *)dataList{
    
    _dataList = dataList;
    
    [self.tableView reloadData];
    [self.collectionView reloadData];
}

- (void)setupUI{
    
    UIButton * startButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 65, 25)];
    [startButton setTitle:@"Start" forState:UIControlStateNormal];
    [startButton setTitleColor:ZRWhiteColor forState:UIControlStateNormal];
    [startButton setBackgroundImage:[self createImageWithColor:[UIColor colorWithHexString:@"32AEFF"]] forState:UIControlStateNormal];
    [startButton addTarget:self action:@selector(clickStartButton) forControlEvents:UIControlEventTouchUpInside];
    startButton.titleLabel.font = [UIFont systemFontOfSize:16];
    startButton.layer.cornerRadius = 8;
    startButton.layer.masksToBounds = YES;
    
    self.startButton = startButton;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.startButton];
    
    
    NSArray *segmentedArray = [NSArray arrayWithObjects:@"Shake",@"Grab",nil];
    //初始化UISegmentedControl
    UISegmentedControl *segment = [[UISegmentedControl alloc]initWithItems:segmentedArray];
    //设置frame
    segment.frame = CGRectMake(60, kNavHeight + 10, kScreenW-120, 32);
    segment.tintColor = [UIColor colorWithHexString:@"32AEFF"];
    segment.selectedSegmentIndex = 0;
    [segment addTarget:self action:@selector(indexDidChangeForSegmentedControl:) forControlEvents:UIControlEventValueChanged];
    segment.layer.cornerRadius = 20;
    segment.layer.borderWidth = 1.0f;
    segment.layer.borderColor = [[UIColor colorWithHexString:@"32AEFF"] CGColor];
    segment.layer.masksToBounds = YES;
    //    segment.tintColor = [UIColor clearColor];
    //    选中的颜色
    [segment setBackgroundImage:[self createImageWithColor:[UIColor colorWithHexString:@"32AEFF"]]
    forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
    [segment setTitleTextAttributes:@{NSForegroundColorAttributeName:ZRWhiteColor} forState:UIControlStateSelected];
    //    未选中的颜色
    [segment setBackgroundImage:[self createImageWithColor:ZRWhiteColor]
    forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [segment setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"32AEFF"]} forState:UIControlStateNormal];
    
    self.segment = segment;
    //添加到视图
    [self.view addSubview:self.segment];
    
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.segment.bottom , kScreenW, self.view.height - self.segment.bottom) style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ZRWhiteColor;//ColorWithRGB(0xEFF0F1);
    tableView.rowHeight = 64;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    self.tableView = tableView;
    
    [self.tableView registerClass:[ChoiceTableViewCell class] forCellReuseIdentifier:@"ChoiceTableViewCell"];
    
    [self.view addSubview:self.tableView];
    
    UILabel * exploreLabel  = [[UILabel alloc] initWithFrame:CGRectMake(0, self.segment.bottom + 20, kScreenW, 20)];

    exploreLabel.text = @"please click on any picture.";
    exploreLabel.textColor = [UIColor colorWithHexString:@"BABABA"];
    exploreLabel.textAlignment = NSTextAlignmentCenter;
    exploreLabel.font = [UIFont systemFontOfSize:16];
    exploreLabel.hidden = YES;
    self.exploreLabel = exploreLabel;
       
    [self.view addSubview:self.exploreLabel];
    //1.初始化layout
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
    layout.itemSize =CGSizeMake(80, 80);
    layout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
        //设置collectionView滚动方向
    //    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        //2.初始化collectionView
    UICollectionView * collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(20, self.exploreLabel.bottom , kScreenW - 40, self.view.height - self.exploreLabel.bottom) collectionViewLayout:layout];
        
    collectionView.backgroundColor = ZRWhiteColor;
    collectionView.showsHorizontalScrollIndicator = NO;
        //3.注册collectionViewCell
    //注意，此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
    [collectionView registerClass:[NumberCollectionViewCell class] forCellWithReuseIdentifier:@"NumberCollectionViewCell"];
        //4.设置代理
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.hidden = YES;
    
    self.collectionView = collectionView;
    
    [self.view addSubview:self.collectionView];
}

-(void)indexDidChangeForSegmentedControl:(UISegmentedControl *)sender{

    if (sender.selectedSegmentIndex == 0) {
        
        self.startButton.hidden = NO;
        self.tableView.hidden = NO;
        self.collectionView.hidden = YES;
        self.exploreLabel.hidden = YES;
        
        [self.tableView reloadData];
    }else{
        
        if (self.dataList.count == 0) {
            
            [self.segment setSelectedSegmentIndex:0];
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                      message:@"Please,add your options first"
                                                                               preferredStyle:UIAlertControllerStyleAlert];
                       
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                                             handler:^(UIAlertAction * action) {
                                                                                 
                                                                                 AddOpinionsViewController * addVC = [AddOpinionsViewController new];
                                                                                 addVC.type = self.type;
                                                                                 [self.navigationController pushViewController:addVC animated:YES];
                
                                                                             }];
                       
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
            
        }else{
            
            self.collectionView.hidden = NO;
            self.exploreLabel.hidden = NO;
            self.tableView.hidden = YES;
            self.startButton.hidden = YES;
            
            [self.collectionView reloadData];
        }
    }
}


- (void)clickStartButton{
    
    if (self.dataList.count == 0) {
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                  message:@"Please,add your options first"
                                                                           preferredStyle:UIAlertControllerStyleAlert];
                   
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                         handler:^(UIAlertAction * action) {
                                                                             
            
                                                                         }];
                   
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        
        ShakeViewController * shakeVC = [ShakeViewController new];
        shakeVC.type = self.type;
        [self.navigationController pushViewController:shakeVC animated:YES];
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == self.dataList.count) {
        
        AddOpinionsViewController * addVC = [AddOpinionsViewController new];
        addVC.type = self.type;
        [self.navigationController pushViewController:addVC animated:YES];
    }else{
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                  message:@"Are you sure delete it?"
                                                                           preferredStyle:UIAlertControllerStyleAlert];
                   
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"Sure" style:UIAlertActionStyleDefault
                                                                         handler:^(UIAlertAction * action) {
                                                                             
            NSMutableArray * arr = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:self.type]];
            [arr removeObjectAtIndex:indexPath.row];
            self.dataList = arr.copy;
                                                                         }];
        UIAlertAction* cancleAction = [UIAlertAction actionWithTitle:@"Cancle" style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * action) {
            
            
                                                                        }];
                   
        [alert addAction:defaultAction];
        [alert addAction:cancleAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataList.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ChoiceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChoiceTableViewCell" forIndexPath:indexPath];
        
    if (indexPath.row == self.dataList.count) {
        
        cell.titleLabel.hidden = YES;
        cell.addImageView.hidden = NO;
        cell.backView.backgroundColor = [UIColor colorWithHexString:@"D3D1EE"];
    }else{
        
        cell.titleLabel.hidden = NO;
        cell.addImageView.hidden = YES;
        cell.titleLabel.text = self.dataList[indexPath.row];
        int colorNum = indexPath.row % 10;
        
        
        cell.backView.backgroundColor = [UIColor colorWithHexString:self.colorArray[colorNum]];
    }
    return cell;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.dataList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    NumberCollectionViewCell *cell = (NumberCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"NumberCollectionViewCell" forIndexPath:indexPath];
    //设置数据
    cell.numberLab.text = [NSString stringWithFormat:@"%ld",indexPath.row + 1];
    
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    [self setupToolBarView];
}


- (void)setupToolBarView{
    
    UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //样式
    toolbar.barStyle = UIBarStyleBlack;//半透明
    //透明度
    toolbar.backgroundColor = ZRBlackColor;
    toolbar.alpha = 0.5f;
    toolbar.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickCloseButton)];
    [toolbar addGestureRecognizer:tapGR];
    
    self.toolbar = toolbar;
    [self.navigationController.view addSubview:self.toolbar];
    
    UIView * whiteView = [[UIView alloc] init];
    
    whiteView.backgroundColor = ZRWhiteColor;
    whiteView.userInteractionEnabled = YES;
    whiteView.layer.cornerRadius = 5;
    
    self.whiteView = whiteView;
    
    [self.navigationController.view addSubview:self.whiteView];

    
    UIButton * closeButton = [UIButton new];
    
    [closeButton setImage:[UIImage imageNamed:@"cancle"] forState:UIControlStateNormal];
    [closeButton addTarget:self action:@selector(clickCloseButton) forControlEvents:UIControlEventTouchUpInside];
    
    [self.whiteView addSubview:closeButton];
    
    UIImageView * toyImageView = [UIImageView new];
    
    toyImageView.image = [UIImage imageNamed:@"small_toy"];
    
    [self.whiteView addSubview:toyImageView];
    
    
    UILabel * titleLab = [UILabel new];
    
    titleLab.text = @"Best Choice";
    titleLab.textColor = ZRBlackColor;
    titleLab.font = [UIFont boldSystemFontOfSize:16];
    titleLab.textAlignment = NSTextAlignmentCenter;
    
    [whiteView addSubview:titleLab];
    
    
    UILabel * reslutLab = [UILabel new];
    
    NSArray * arr = [[NSUserDefaults standardUserDefaults] objectForKey:self.type];
    int x = arc4random() % arr.count;
    reslutLab.text = arr[x];
    reslutLab.textColor = [UIColor colorWithHexString:@"F26760"];
    reslutLab.font = [UIFont boldSystemFontOfSize:24];
    reslutLab.textAlignment = NSTextAlignmentCenter;
    
    [whiteView addSubview:reslutLab];
    
    
    [self.whiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.centerY.mas_equalTo(self.view);
        make.width.mas_equalTo(176);
        make.height.mas_equalTo(194);
    }];
    
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.whiteView.mas_bottom).offset(20);
        make.width.height.mas_equalTo(48);
    }];
    
    [toyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.centerY.mas_equalTo(self.whiteView.mas_top);
        make.width.mas_equalTo(144);
        make.height.mas_equalTo(100);
    }];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.whiteView);
        make.width.mas_equalTo(150);
        make.top.mas_equalTo(toyImageView.mas_bottom).offset(5);
    }];

    [reslutLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.whiteView);
        make.width.mas_equalTo(150);
        make.top.mas_equalTo(titleLab.mas_bottom).offset(30);
    }];
}


- (void)clickCloseButton{
    
    [self.toolbar removeFromSuperview];
    [self.whiteView removeFromSuperview];
}

- (UIImage*) createImageWithColor: (UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}


- (NSArray *)colorArray{
    
    if (!_colorArray) {
        
        _colorArray = @[@"0089FF",@"2ACC9E",@"86E62E",@"F2D230",@"FF8233",@"A966FE",@"FFC5AD",@"F390D2",@"34D5DA",@"687FF9"];
    }
    
    return _colorArray;
}

@end
